package com.villaday.idf.activity;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.villaday.idf.R;
import com.villaday.idf.adapter.HouseMoneyManageAdapter;
import com.villaday.idf.base.BaseActivity;
import com.villaday.idf.custom.LoadDialog;
import com.villaday.idf.custom.pop.CalendarPop;
import com.villaday.idf.custom.pop.DataPop;
import com.villaday.idf.custom.pop.RefusePop;
import com.villaday.idf.model3.HashInfosEntity;
import com.villaday.idf.model3.HashPrice;
import com.villaday.idf.model3.HashPricesEntity;
import com.villaday.idf.model3.StatesPostEntity;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.SharedPreferencesUtil;
import com.villaday.idf.util.StatusBarUtil;
import com.villaday.idf.util.ToastUtil;
import com.villaday.idf.util.ToolBarUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class HouseMoneyManageActivity extends BaseActivity {


    @BindView(R.id.toolbar_back)
    ImageButton toolbarBack;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.toolbar_next)
    TextView toolbarNext;
    @BindView(R.id.Line_view)
    View LineView;
    @BindView(R.id.toolbar_text)
    Toolbar toolbarText;
    @BindView(R.id.tv_hmm_retire)
    TextView tvHmmRetire;
    @BindView(R.id.tv_hmm_add)
    TextView tvHmmAdd;
    @BindView(R.id.rv_hmm)
    RecyclerView rvHmm;
    @BindView(R.id.ll_hmm_manage)
    TextView llHmmManage;
    @BindView(R.id.tv_hmm_name)
    TextView tvHmmName;
    @BindView(R.id.tv_hmm_type)
    TextView tvHmmType;
    @BindView(R.id.tv_hmm_sunday)
    TextView tvHmmSunday;
    @BindView(R.id.tv_hmm_monday)
    TextView tvHmmMonday;
    @BindView(R.id.tv_hmm_tuesday)
    TextView tvHmmTuesday;
    @BindView(R.id.tv_hmm_wednesday)
    TextView tvHmmWednesday;
    @BindView(R.id.tv_hmm_thursday)
    TextView tvHmmThursday;
    @BindView(R.id.tv_hmm_friday)
    TextView tvHmmFriday;
    @BindView(R.id.tv_hmm_saturday)
    TextView tvHmmSaturday;
    @BindView(R.id.tv_hmm_money)
    TextView tvHmmMoney;
    @BindView(R.id.tv_hmm_time)
    TextView tvHmmTime;
    @BindView(R.id.tv_hmm_not)
    TextView tvHmmNot;

    private String mHouseId;
    private HouseMoneyManageAdapter mHouseMoneyManageAdapter;
    private LoadDialog mLoadDialog;
    private HashPricesEntity.BodyBean mBody;
    private String mHouseName;
    private HashInfosEntity.BodyBean mInfoBody;


    @Override
    protected int getViewResId() {
        return R.layout.activity_house_money_manage;
    }

    @Override
    protected void init() {
        super.init();
        StatusBarUtil.setTranslucentForImageViewInFragment(this, null);
        StatusBarUtil.setLightMode(this);

        toolbarText.setBackgroundResource(R.color.colorBackground);
        ToolBarUtil.initToolBar(toolbarText, "房价管理", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        mHouseId = getIntent().getExtras().getString("houseId");
        mHouseName = getIntent().getExtras().getString("houseName");

        showDialog();

        tvHmmName.setText(mHouseName);
        initRecycle();
        getDetails();
        getInfo();
    }

    private void getInfo() {
        Map<String, String> map = new HashMap<>();
        OkHttpUtil.getJSON(this, String.format(Constant.URL.hashInfos, SharedPreferencesUtil.getRoleInfoId(this)), map, new OkHttpUtil.OnDataListener() {
            @Override
            public void onResponse(String url, String json) {
                try {
                    LogUtil.jLog().e(json);
                    HashInfosEntity hashInfosEntity = new Gson().fromJson(json, HashInfosEntity.class);
                    if (hashInfosEntity.getCode().equals(Constant.Strings.SUC)) {
                        mInfoBody = hashInfosEntity.getBody();
                        tvHmmType.setText(hashInfosEntity.getBody().getSettlementMode());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String url, String error) {

            }
        });
    }


    private void getDetails() {
        Map<String, String> map = new HashMap<>();
        map.put("merchantId", SharedPreferencesUtil.getRoleInfoId(this));
        map.put("houseId", mHouseId);
        OkHttpUtil.getJSON(this, String.format(Constant.URL.hashPrices, SharedPreferencesUtil.getRoleInfoId(this), mHouseId), map, new OkHttpUtil.OnDataListener() {
            @Override
            public void onResponse(String url, String json) {
                try {
                    LogUtil.jLog().e(json);
                    dismissDialog();
                    HashPricesEntity hashPricesEntity = new Gson().fromJson(json, HashPricesEntity.class);
                    if (hashPricesEntity.getCode().equals(Constant.Strings.SUC)) {
                        mBody = hashPricesEntity.getBody();
                        HashPricesEntity.BodyBean.WeekBean week = hashPricesEntity.getBody().getWeek();
                        if (week.getStartDate() != null && week.getEndDate() != null
                                && !TextUtils.isEmpty(week.getStartDate()) && !TextUtils.isEmpty(week.getEndDate())) {
                            tvHmmTime.setVisibility(View.VISIBLE);
                            tvHmmTime.setText("有效期：" + week.getStartDate().replaceAll("-", "/") + " — " + week.getEndDate().replaceAll("-", "/"));
                        } else {
                            tvHmmTime.setVisibility(View.GONE);
                        }
                        tvHmmMonday.setText(week.getMondayPrice());
                        tvHmmSaturday.setText(week.getSaturdayPrice());
                        tvHmmFriday.setText(week.getFridayPrice());
                        tvHmmThursday.setText(week.getThursdayPrice());
                        tvHmmSunday.setText(week.getSundayPrice());
                        tvHmmWednesday.setText(week.getWednesdayPrice());
                        tvHmmTuesday.setText(week.getTuesdayPrice());

                        if (mBody.getDates().size() > 0) {
                            rvHmm.setVisibility(View.VISIBLE);
                            tvHmmNot.setVisibility(View.GONE);
                            mHouseMoneyManageAdapter.setData(mBody.getDates());
                        } else {
                            rvHmm.setVisibility(View.GONE);
                            tvHmmNot.setVisibility(View.VISIBLE);
                        }
                    } else {

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }


            }

            @Override
            public void onFailure(String url, String error) {

            }
        });
    }

    private void initRecycle() {
        rvHmm.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mHouseMoneyManageAdapter = new HouseMoneyManageAdapter(this, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final int position = (int) v.getTag();
                switch (v.getId()) {
                    case R.id.iv_hmm_retire:
                        DataPop dataPop = new DataPop(HouseMoneyManageActivity.this, HouseMoneyManageActivity.this, mHouseId, mHouseName, mInfoBody.getSettlementMode(), "特殊修改", new Gson().toJson(mBody.getDates().get(position)));
                        dataPop.setOnBtnClickListener(new DataPop.OnBtnClickListener() {
                            @Override
                            public void onBtnClick(String title) {
                                showDialog();
                                getDetails();
                            }
                        });
                        dataPop.showPopupWindow();
                        break;
                    case R.id.iv_hmm_delete:
                        RefusePop phonePopular = new RefusePop(HouseMoneyManageActivity.this, "删除");
                        phonePopular.setOnBtnClickListener(new RefusePop.OnBtnClickListener() {
                            @Override
                            public void onBtnClick(View view, String title) {
                                showDialog();
                                Map<String, Object> map = new HashMap<>();
                                HashPrice hashPrice = new HashPrice();
                                hashPrice.setAction(6);
                                hashPrice.setId(mBody.getDates().get(position).getId());
                                hashPrice.setMode(2);
//                                hashPrice.setStartDate(mBody.getDates().get(position).getStartDate());
//                                hashPrice.setEndDate(mBody.getDates().get(position).getEndDate());
                                hashPrice.setCostPrice(mBody.getDates().get(position).getCostPrice());
                                LogUtil.jLog().e(new Gson().toJson(hashPrice));
                                OkHttpUtil.postJson(HouseMoneyManageActivity.this, String.format(Constant.URL.hashPrices, SharedPreferencesUtil.getRoleInfoId(HouseMoneyManageActivity.this), mHouseId), hashPrice, map, new OkHttpUtil.OnDataListener() {
                                    @Override
                                    public void onResponse(String url, String json) {
                                        try {
                                            LogUtil.jLog().e(json);
                                            dismissDialog();
                                            StatesPostEntity statesPostEntity = new Gson().fromJson(json, StatesPostEntity.class);
                                            if (statesPostEntity.getCode().equals(Constant.Strings.SUC) && statesPostEntity.isBody()) {
                                                ToastUtil.initToast(getApplicationContext(), "删除成功");
                                                showDialog();
                                                getDetails();
                                            } else {
                                                ToastUtil.initToast(getApplicationContext(), statesPostEntity.getMsg());
                                            }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }

                                    @Override
                                    public void onFailure(String url, String error) {

                                    }
                                });

                            }
                        });
                        phonePopular.showPopupWindow();
                        break;
                }
            }
        });
        rvHmm.setAdapter(mHouseMoneyManageAdapter);
    }

    @OnClick({R.id.ll_hmm_manage, R.id.tv_hmm_retire, R.id.tv_hmm_add, R.id.ll_hmm_house})
    public void btnOnclick(View view) {
        switch (view.getId()) {
            case R.id.tv_hmm_retire:
                DataPop dataPop = new DataPop(this, HouseMoneyManageActivity.this, mHouseId, mHouseName, mInfoBody.getSettlementMode(), "通用", new Gson().toJson(mBody));
                dataPop.setOnBtnClickListener(new DataPop.OnBtnClickListener() {
                    @Override
                    public void onBtnClick(String title) {
                        showDialog();
                        getDetails();
                    }
                });
                dataPop.showPopupWindow();
                break;
            case R.id.ll_hmm_manage:
                CalendarPop calendarPopManage = new CalendarPop(this, mHouseId, mHouseName, new Gson().toJson(mInfoBody), 1);
                calendarPopManage.showPopupWindow();
                break;
            case R.id.tv_hmm_add:
                CalendarPop calendarPop = new CalendarPop(this, mHouseId, mHouseName, new Gson().toJson(mInfoBody), 0);
                calendarPop.setOnBtnClickListener(new CalendarPop.OnBtnClickListener() {
                    @Override
                    public void onBtnClick(String title) {
                        showDialog();
                        getDetails();
                    }
                });
                calendarPop.showPopupWindow();
                break;
            case R.id.ll_hmm_house:
                initInstallApp(mInfoBody.getHouses());
                break;
        }
    }


    private void initInstallApp(final List<HashInfosEntity.BodyBean.HousesBean> houses) {
        final ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < houses.size(); i++) {
            list.add(houses.get(i).getName());
        }
        OptionsPickerView<String> mOptionsPickerView = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                LogUtil.jLog().e(options1);
                String id = houses.get(options1).getId();
                mHouseId = id;
                tvHmmName.setText(houses.get(options1).getName());
                showDialog();
                getDetails();
            }
        }).setCancelColor(getResources().getColor(R.color.colorRed))
                .setSubmitColor(getResources().getColor(R.color.colorRed)).build();
        // 设置数据
        mOptionsPickerView.setPicker(list);

        for (int i = 0; i < list.size(); i++) {
            if (tvHmmName.getText().toString().equals(list.get(i))) {
                mOptionsPickerView.setSelectOptions(i);
            }
        }


        // 设置选项单位
        mOptionsPickerView.show();
    }


    /**
     * 设置加载框
     */
    protected void showDialog() {
        if (mLoadDialog == null) {
            mLoadDialog = LoadDialog.newInstance("加载中");
        }
        mLoadDialog.show(getSupportFragmentManager(), "loading");
    }

    /**
     * 设置加载框
     */
    protected void dismissDialog() {
        if (mLoadDialog != null) {
            mLoadDialog.dismiss();
        }
    }
}
